package com.ysx.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysx.article.feign.ApAuthorFeign;
import com.ysx.article.pojo.ApAuthor;
import com.ysx.behaviour.dto.FollowBehaviorDto;
import com.ysx.common.constants.BusinessConstants;
import com.ysx.exception.ToutiaoException;
import com.ysx.user.dto.UserRelationDto;
import com.ysx.user.mapper.ApUserFanMapper;
import com.ysx.user.mapper.ApUserFollowMapper;
import com.ysx.user.mapper.ApUserMapper;
import com.ysx.user.pojo.ApUser;
import com.ysx.user.pojo.ApUserFan;
import com.ysx.user.pojo.ApUserFollow;
import com.ysx.user.service.ApUserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 1.判断条件检查参数
 2.获取操作类型 要关注还是取消关注
 3.根据文章ID 获取作者信息 并获取作者对应的APP userid的值
 4.判断是否为关注 还是取消关注 如果是关注
 4.1先查询是否已有关注表记录
 4.2再查询是否有粉丝表记录
 4.3进行数据封装 最终存储到数据库表中即可
 5.如果是取消关注
 */
@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;//用户关注的作者 Mapper

    @Autowired
    private ApUserFanMapper apUserFanMapper;//用户的粉丝 Mapper

    @Autowired
    private ApAuthorFeign apAuthorFeign;//作者 Mapper

    @Autowired
    private ApUserMapper apUserMapper;//用户 Mapper

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;


    @Override
    @Transactional(rollbackFor = {Exception.class, ToutiaoException.class})
    public void followUserByWho(UserRelationDto relationDto, Integer currentUserId)  throws Exception{
        //1.获取操作类型
        if (relationDto.getOperation() == null || relationDto.getOperation() < 0 || relationDto.getOperation() > 1) {
            throw new ToutiaoException("错误的操作类型");
        }
        if(StringUtils.isEmpty(relationDto.getAuthorId())){
            throw new ToutiaoException("作者ID不能为空");
        }
        //先根据作者的ID 获取用该作者对应的APP用户的ID 值 再进行操作
        ApAuthor data = apAuthorFeign.findById(relationDto.getAuthorId()).getData();

        if(data==null){
            throw new ToutiaoException("没有该作者");
        }
        //进行关注
        if (relationDto.getOperation() == 1) {
            //2.判断如果是关注 则需要保存数据到 follow和fan表中
            //2.1先查询是否有该记录在关注表，如果有就不需要再关注了 说明接口调用有业务流程的问题
            QueryWrapper<ApUserFollow> queryWrapper1 = new QueryWrapper<ApUserFollow>();
            queryWrapper1.eq("user_id",currentUserId);
            queryWrapper1.eq("follow_id",data.getUserId());
            ApUserFollow userFollow = apUserFollowMapper.selectOne(queryWrapper1);
            if(userFollow!=null){
                throw new ToutiaoException("关注表已经存在记录");
            }
            userFollow = new ApUserFollow();

            userFollow.setCreatedTime(LocalDateTime.now());
            //关注人
            userFollow.setUserId(currentUserId);
            //被关注人ID 作者对应的 appUserID的值
            userFollow.setFollowId(data.getUserId());
            //被关注人名称 作者对应的 appUser的名称 由于作者名称和appUser表中的名字一样，所以可以用他，页面传递过来作者名称即可
            userFollow.setFollowName(relationDto.getAuthorName());
            //暂时硬编码
            userFollow.setLevel(0);
            userFollow.setIsNotice(1);

            //2.2 添加至数据库中
            apUserFollowMapper.insert(userFollow);

            //2.3 查询 是否存在关联表 如果有 则说明已经存在 抛出异常，有问题
            QueryWrapper<ApUserFan> queryWrapper2 = new QueryWrapper<ApUserFan>();
            queryWrapper2.eq("user_id",data.getUserId());//作者对应的 APP用户的ID
            queryWrapper2.eq("fans_id",currentUserId);// 粉丝ID 就是当前的用户的ID

            ApUserFan apUserFan = apUserFanMapper.selectOne(queryWrapper2);
            if(apUserFan!=null){
                throw new ToutiaoException("粉丝表数据已经存在");
            }
            apUserFan = new ApUserFan();
            apUserFan.setCreatedTime(LocalDateTime.now());
            //作者对应的 APPUSER的id
            apUserFan.setUserId(data.getUserId());
            //作者粉丝的ID 就是当前用户
            apUserFan.setFansId(currentUserId);

            //粉丝的名称 即为当前用户的名称
            ApUser apUser = apUserMapper.selectById(currentUserId);
            if(apUser==null){
                throw new ToutiaoException("用户不存在");
            }
            apUserFan.setFansName(apUser.getName());

            apUserFan.setLevel(0);
            apUserFan.setIsDisplay(1);
            apUserFan.setIsShieldLetter(0);
            apUserFan.setIsShieldComment(0);
            apUserFanMapper.insert(apUserFan);


            //关注完了之后发送消息

            //记录关注行为
            FollowBehaviorDto dto = new FollowBehaviorDto();
            //被关注者 用户的ID
            dto.setFollowId(data.getUserId());
            //关注者 用户的ID
            dto.setUserId(currentUserId);
            //文章
            dto.setArticleId(relationDto.getArticleId());

            /*
             * 异步发送消息 记录用户行为
             */
            kafkaTemplate.send(BusinessConstants.MqConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));




        } else {
            //3.判断如果是取消关注 则需要删除 fan follow中的关系数据
            QueryWrapper<ApUserFollow> queryWrapper1 = new QueryWrapper<ApUserFollow>();
            queryWrapper1.eq("user_id",currentUserId);
            queryWrapper1.eq("follow_id",data.getUserId());
            apUserFollowMapper.delete(queryWrapper1);

            QueryWrapper<ApUserFan> queryWrapper2 = new QueryWrapper<ApUserFan>();
            queryWrapper2.eq("user_id",data.getUserId());//作者对应的 APP用户的ID
            queryWrapper2.eq("fans_id",currentUserId);// 粉丝ID 就是当前的用户的ID
            apUserFanMapper.delete(queryWrapper2);

        }
    }

}
